<template>
  <GenericTableManager
    title="用户管理"
    @search="handleSearch"
    @add="handleAdd"
    @edit="handleEdit"
    @delete="handleDelete"
    @export="handleExport"
    @import="handleImport"
    @refresh="handleRefresh"
    @submit="handleSubmit"
    @selection-change="handleSelectionChange"
    ref="tableManagerRef"
  >
    <!-- 搜索表单插槽 -->
    <template #search="{ searchForm, handleSearch, handleReset, loading }">
      <el-form :model="searchForm" :inline="true" @submit.prevent="handleSearch">
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.userName"
            placeholder="请输入用户名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch" :loading="loading">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </template>

    <!-- 操作按钮插槽 -->
    <template #actions="{ handleAdd, handleExport, handleImport, handleRefresh, selectedRows, loading }">
      <el-button type="primary" :icon="Plus" @click="handleAdd">新增用户</el-button>
      <el-button type="success" :icon="Download" @click="handleExport" :loading="loading">导出</el-button>
      <el-button type="warning" :icon="Upload" @click="handleImport" :loading="loading">导入</el-button>
      <el-button v-if="selectedRows.length > 0" type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
    </template>

    <!-- 表格列插槽 -->
    <template #columns="{ tableData, handleEdit, handleDelete }">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="userId" label="用户ID" width="80" />
      <el-table-column prop="userName" label="用户名" width="120" />
      <el-table-column prop="nickName" label="昵称" width="120" />
      <el-table-column prop="email" label="邮箱" width="180" />
      <el-table-column prop="phoneNumber" label="手机号" width="120" />
      <el-table-column prop="deptName" label="部门" width="120" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === '0' ? 'success' : 'danger'">
            {{ row.status === '0' ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
          <el-button type="warning" size="small" :icon="Key" @click="handleResetPassword(row)">重置密码</el-button>
          <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </template>

    <!-- 表单插槽 -->
    <template #form="{ formData, formRules, formRef, isEdit, loading }">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input
                v-model="formData.userName"
                placeholder="请输入用户名"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickName">
              <el-input
                v-model="formData.nickName"
                placeholder="请输入昵称"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="formData.email"
                placeholder="请输入邮箱"
                type="email"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phoneNumber">
              <el-input
                v-model="formData.phoneNumber"
                placeholder="请输入手机号"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="formData.status"
                placeholder="请选择状态"
                style="width: 100%"
              >
                <el-option label="正常" value="0" />
                <el-option label="停用" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <el-tree-select
                v-model="formData.deptId"
                :data="deptOptions"
                :props="{ value: 'id', label: 'name', children: 'children' }"
                placeholder="请选择部门"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="角色" prop="roleIds">
          <el-select
            v-model="formData.roleIds"
            multiple
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="role in roleOptions"
              :key="role.roleId"
              :label="role.roleName"
              :value="role.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
    </template>
  </GenericTableManager>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Plus, Download, Upload, Edit, Key, Delete } from '@element-plus/icons-vue'
import GenericTableManager from '@/components/GenericTableManager.vue'
import { useUserTableManager } from '@/composables/useTableManager'
import type { UserInfo, UserQuery, UserForm } from '@/types/user'
import type { Dept, Role } from '@/types/system'
import { getUserListApi, addUserApi, updateUserApi, deleteUserApi } from '@/api/user'

// 使用通用表格管理
const {
  tableData,
  loading,
  pagination,
  searchForm,
  selectedRows,
  handleSearch,
  handleReset,
  handleAdd,
  handleEdit,
  handleDelete,
  handleBatchDelete,
  handleSubmit,
  handleExport,
  handleImport,
  handleRefresh,
  handleSelectionChange,
  setFormRules,
  setSearchForm
} = useUserTableManager()

// 表格管理器引用
const tableManagerRef = ref()

// 选项数据
const deptOptions = ref<Dept[]>([])
const roleOptions = ref<Role[]>([])

// 表单验证规则
const formRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 初始化
onMounted(() => {
  setFormRules(formRules)
  setSearchForm({
    userName: '',
    status: ''
  })
})

// 重置密码
const handleResetPassword = async (row: UserInfo) => {
  try {
    await ElMessageBox.confirm('确定要重置该用户的密码吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里调用重置密码API
    ElMessage.success('密码重置成功')
  } catch {
    // 用户取消操作
  }
}
</script>

<style scoped lang="scss">
// 样式已由 GenericTableManager 组件提供
</style>
